<template>
  <q-card flat class="q-pa-sm">
    <q-form
      @submit.prevent="onSubmit"
      @reset="onReset"
      @validation-error="errorMsg"
    >
      <TabContainer>
        <!-- <TabContainer :bot-margin="100"> -->

        <div class="page-header row justify-between">
          <div class="col-8" v-if="myForm == 'create'">
            <div class="fal">
              <q-item-section avatar>
                <img style="height: 1.7rem" :src="writeIcon" />
              </q-item-section>
              Create New Item - {{ level }}
            </div>
          </div>
          <div class="col-8" v-if="myForm == 'edit'">
            Edit Item - {{ level }}
          </div>
          <q-select
            borderless
            class="col-4 input-css"
            style="width: auto"
            :dense="true"
            v-model="level"
            :options="levelOps"
            :disable="myForm == 'edit' || level == 'level 5'"
          />
        </div>
        <q-card flat class="row">
          <div class="col-12">
            <div class="q-pa-md q-ma-sm">
              <div class="sub-header fal">
                <q-item-section avatar>
                  <img style="height: 1.4rem" :src="penIcon" />
                </q-item-section>

                Enter Details
              </div>
              <div class="row">
                <div class="col-4 fal">
                  <q-item-label>Stock Code:</q-item-label
                  ><span style="color: red">*</span>
                </div>
                <div class="col-8 q-pa-sm">
                  <q-input
                    borderless
                    class="input-css"
                    v-model="newItemForm.stockCode"
                    use-input
                    :dense="true"
                    hide-bottom-space
                    :disable="myForm == 'edit'"
                    :rules="[checkStockCode]"
                  >
                  </q-input>
                </div>

                <div class="col-4 fal">
                  <q-item-label>Work Group:</q-item-label
                  ><span style="color: red">*</span>
                </div>
                <div class="col-8 q-pa-sm">
                  <q-select
                    borderless
                    class="input-css"
                    v-model="newItemForm.workgroup"
                    :options="inputOptionStore.data.workgroup"
                    stack-label
                    :dense="true"
                    lazy-rules
                    hide-bottom-space
                    :rules="[(val) => val.length > 0 || 'Require field']"
                  />
                </div>

                <div class="col-4 fal">
                  <q-item-label>System:</q-item-label
                  ><span style="color: red">*</span>
                </div>
                <div class="col-8 q-pa-sm">
                  <q-select
                    borderless
                    class="input-css"
                    v-model="newItemForm.system"
                    :options="inputOptionStore.data.system"
                    stack-label
                    :dense="true"
                    lazy-rules
                    hide-bottom-space
                    :rules="[(val) => val.length > 0 || 'Require field']"
                  />
                </div>

                <div class="col-4 fal">
                  <q-item-label>Short Description:</q-item-label
                  ><span style="color: red">*</span>
                </div>
                <div class="col-8 q-pa-sm">
                  <q-input
                    borderless
                    class="input-css"
                    v-model="newItemForm.shortDescription"
                    :dense="true"
                    lazy-rules
                    hide-bottom-space
                    :rules="[(val) => val.length > 0 || 'Require field']"
                  />
                </div>

                <div class="col-4 fal">
                  <q-item-label>Description:</q-item-label>
                </div>
                <div class="col-8 q-pa-sm">
                  <div style="max-width: 300px">
                    <q-input
                      borderless
                      v-model="newItemForm.detailDescription"
                      class="text-area-css"
                      type="textarea"
                    />
                  </div>
                </div>

                <div class="col-4 fal">
                  <q-item-label>Date Code:</q-item-label>
                </div>
                <div class="col-8 q-pa-sm">
                  <div style="max-width: 300px">
                    <q-input
                      borderless
                      class="input-css"
                      v-model="newItemForm.dateCode"
                      dense
                      hide-bottom-space
                      :rules="[(val) => dateCodeRule(val)]"
                    >
                      <template v-slot:append>
                        <q-icon
                          class="cursor-pointer"
                          size="md"
                          @click="datePopup = true"
                        >
                          <img :src="dateIcon" />
                        </q-icon>
                      </template>
                    </q-input>
                  </div>
                </div>
                <q-dialog v-model="datePopup">
                  <DateCodeSelect
                    @update="updateCreateFormDateCode"
                  ></DateCodeSelect>
                </q-dialog>

                <div class="col-4 fal">
                  <div class="fac">
                    <q-item-label>S/W Version:</q-item-label>
                  </div>
                </div>
                <div class="col-8 q-pa-sm">
                  <q-input
                    borderless
                    class="input-css"
                    v-model="newItemForm.swVer"
                    :dense="true"
                  />
                  <span class="text-indigo-8 text-body2">
                    Multiple version example: version1,version2
                  </span>
                </div>

                <div class="col-4 fal">
                  <div class="fac">
                    <q-item-label>H/W Version:</q-item-label>
                  </div>
                </div>
                <div class="col-8 q-pa-sm">
                  <q-input
                    borderless
                    class="input-css"
                    v-model="newItemForm.hwVer"
                    :dense="true"
                  />
                  <span class="text-indigo-8 text-body2">
                    Multiple version example: version1,version2
                  </span>
                </div>

                <div class="col-4 fal">
                  <div class="fac">
                    <q-item-label>Global Regular Cycle Month:</q-item-label>
                  </div>
                </div>
                <div class="col-8 q-pa-sm">
                  <q-input
                    borderless
                    class="input-css"
                    type="number"
                    :min="min_month"
                    :max="max_month"
                    v-model="newItemForm.global_regular_cycle_month"
                    :dense="true"
                  />
                </div>

                <div class="col-4 fal">
                      <q-item-label>Obsolescence:</q-item-label>
                </div>
                <div class="col-8 q-pa-sm">
                  <q-radio
                    v-model="newItemForm.obsolescence"
                    :val="1"
                    label="Yes"
                  />
                  <q-radio
                    v-model="newItemForm.obsolescence"
                    :val="0"
                    label="No"
                  />
                </div>
              </div>

              <div class="text-h6">Asset Hierarchy</div>
              <div class="row">
                <div class="col-4 fal">
                  <q-item-label>Asset ID:</q-item-label>
                </div>
                <div class="col-8 q-pa-sm">
                  <q-input
                    borderless
                    class="input-css"
                    v-model="newItemForm.asset_id"
                    :dense="true"
                  />
                </div>

                <div class="col-4 fal">
                  <q-item-label>Equipment Class:</q-item-label
                  ><span style="color: red">*</span>
                </div>
                <div class="col-6 q-pa-sm">
                  <q-select
                    borderless
                    class="input-css"
                    v-model="newItemForm.equipmentClass"
                    :options="
                      level == 'level 4'
                        ? inputOptionStore.data.equipmentClassLv4
                        : inputOptionStore.data.equipmentClassLv5
                    "
                    stack-label
                    :dense="true"
                    lazy-rules
                    use-input
                    @filter="epClassFilterFn"
                    hide-bottom-space
                    :rules="[(val) => val.length > 0 || 'Require field']"
                  />
                </div>
                <div class="col-2 q-pa-sm fal">
                  <q-icon
                    class="cursor-pointer"
                    size="md"
                    @click="importECRelation"
                  >
                    <img :src="searchIcon" />
                  </q-icon>
                </div>

                <div class="col-4 fal">
                  <q-item-label>Level 1:</q-item-label
                  ><span style="color: red">*</span>
                </div>
                <div class="col-8 q-pa-sm">
                  <q-select
                    borderless
                    class="input-css"
                    v-model="newItemForm.lv1"
                    :options="inputOptionStore.data.lv1"
                    stack-label
                    :dense="true"
                    lazy-rules
                    hide-bottom-space
                    :rules="[(val) => val.length > 0 || 'Require field']"
                  />
                </div>

                <div class="col-4 fal">
                  <q-item-label>Level 2:</q-item-label
                  ><span style="color: red">*</span>
                </div>
                <div class="col-8 q-pa-sm">
                  <q-select
                    borderless
                    class="input-css"
                    v-model="newItemForm.lv2"
                    :options="inputOptionStore.data.lv2"
                    stack-label
                    :dense="true"
                    lazy-rules
                    hide-bottom-space
                    :rules="[(val) => val.length > 0 || 'Require field']"
                  />
                </div>

                <div class="col-4 fal">
                  <q-item-label>Level 3:</q-item-label
                  ><span style="color: red">*</span>
                </div>
                <div class="col-8 q-pa-sm">
                  <q-select
                    borderless
                    class="input-css"
                    v-model="newItemForm.lv3"
                    :options="inputOptionStore.data.lv3"
                    stack-label
                    :dense="true"
                    lazy-rules
                    hide-bottom-space
                    :rules="[(val) => val.length > 0 || 'Require field']"
                  />
                </div>

                <div class="col-4 fal">
                  <q-item-label>Level 4:</q-item-label
                  ><span style="color: red">*</span>
                </div>
                <div class="col-6 q-pa-sm">
                  <q-select
                    borderless
                    class="input-css"
                    v-model="newItemForm.lv4"
                    :options="inputOptionStore.data.lv4"
                    stack-label
                    :dense="true"
                    lazy-rules
                    use-input
                    hide-bottom-space
                    :rules="[(val) => val.length > 0 || 'Require field']"
                    @filter="lv4FilterFn"
                  >
                  </q-select>
                </div>
                <div class="col-2 q-pa-sm fal">
                  <q-icon
                    v-if="level == 'level 4'"
                    class="cursor-pointer"
                    size="md"
                    @click="importLv4Relation"
                  >
                    <img :src="searchIcon" />
                  </q-icon>
                </div>

                <div class="col-4 fal" v-if="level == 'level 5'">
                  <q-item-label
                    >Level 5:<span style="color: red">*</span>
                  </q-item-label>
                </div>
                <div class="col-6 q-pa-sm" v-if="level == 'level 5'">
                  <q-select
                    borderless
                    class="input-css"
                    hide-bottom-space
                    v-model="newItemForm.lv5"
                    :options="inputOptionStore.data.lv5"
                    stack-label
                    use-input
                    :dense="true"
                    :rules="[(val) => val.length > 0 || 'Require field']"
                    @filter="lv5FilterFn"
                  />
                </div>

                <div class="col-2 q-pa-sm fal" v-if="level == 'level 5'">
                  <q-icon
                    class="cursor-pointer"
                    size="md"
                    @click="importLv5Relation"
                  >
                    <img :src="searchIcon" />
                  </q-icon>
                </div>
              </div>
            </div>
          </div>
        </q-card>
      </TabContainer>

      <q-card-actions class="justify-evenly q-pa-md test">
        <q-btn type="reset" class="blue-btn">Reset</q-btn>
        <q-btn type="submit" :disable="disableSubmit" class="default-btn"
          >Save</q-btn
        >
      </q-card-actions>
    </q-form>
  </q-card>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ItemForm, StockItem } from 'src/services/type';
import {
  getStockItem,
} from 'src/services/stockCodeService';
import { useQuasar } from 'quasar';
import { useChildMapStore } from 'src/stores/childMapStore';
import { useInputOption } from 'src/stores/inputOptionStore';
import DateCodeSelect from 'src/components/DateCodeSelect.vue';
import searchIcon from 'src/assets/style/search.png';

import writeIcon from 'src/assets/style/write.png';
import penIcon from 'src/assets/style/pen.png';
import dateIcon from 'src/assets/style/date.png';
import TabContainer from 'src/components/container/TabContainer.vue';
import {
  importAssetECRelation,
  importAssetLv4Relation,
  importAssetLv5Relation,
} from 'src/services/eqipmentService';

const inputOptionStore = useInputOption();
inputOptionStore.init();

const useChildMap = useChildMapStore();

const props = defineProps<{
  stockItem?: StockItem;
  from: 'edit' | 'create';
  lv: 'level 4' | 'level 5';
  parent_stock_code?: string;
  fixBtn?: boolean;
}>();

const levelOps = ['level 4', 'level 5'];
const level = ref('');
const $q = useQuasar();
const disableSubmit = ref(false);
const datePopup = ref(false);
const min_month = ref<number>(1);
const max_month = ref<number>(32767);

const myForm = ref('')

if (props.lv == 'level 4'){
  level.value ='level 4'
}else{
  level.value ='level 5'
}

if (props.from=='create'){
  myForm.value = 'create'
}else{
  myForm.value = 'edit'
}

const newItemForm: ItemForm = reactive({
  stockCode: '',
  car: '',
  workgroup: '',
  system: '',
  shortDescription: '',
  detailDescription: '',
  dateCode: '',
  swVer: '',
  hwVer: '',
  asset_id: '',
  global_regular_cycle_month: 36,
  obsolescence: 0,
  equipmentClass: '',
  lv1: '',
  lv2: '',
  lv3: '',
  lv4: '',
  lv5: '',
  parent_stock_item_stock_code: '',
});

/* watch(
  () => newItemForm.lv4,
  (lv4) => {
    const selected = inputOptionStore.mapping(lv4);
    if (selected) {
      newItemForm.lv1 = selected.lv1;
      newItemForm.lv2 = selected.lv2;
      newItemForm.lv3 = selected.lv3;
      newItemForm.equipmentClass = selected.class;
    }
    if (props.from == 'edit') {
      getStockItemData();
    }
  }
); */

if (props.stockItem) {
  init();
}

async function getStockItemData() {
  if (props.stockItem) {
    const res = await getStockItem(props.stockItem?.id);
    if (res.data) {
      newItemForm.stockCode = res.data.stock_code;
      newItemForm.workgroup = res.data.workgroup;
      newItemForm.system = res.data.system;
      newItemForm.car = res.data.car;
      newItemForm.shortDescription = res.data.description;
      newItemForm.detailDescription = res.data.detail_description;
      newItemForm.dateCode = res.data.date_code;
      newItemForm.asset_id = res.data.asset_id;
      newItemForm.swVer = res.data.sw_ver;
      newItemForm.hwVer = res.data.hw_ver;
      newItemForm.obsolescence = res.data.obsolescence;
      newItemForm.global_regular_cycle_month = res.data.global_regular_cycle_month;
      newItemForm.equipmentClass = res.data.equipment_class;
      newItemForm.lv1 = res.data.lv1;
      newItemForm.lv2 = res.data.lv2;
      newItemForm.lv3 = res.data.lv3;
      newItemForm.lv4 = res.data.lv4;
      newItemForm.lv5 = res.data.lv5;
    }
  }
}

const emit = defineEmits(['cancel', 'close', 'submit']);

function errorMsg() {
  $q.notify({
    color: 'negative',
    position: 'bottom',
    message: 'Check Require Felid',
  });
}

async function submitForm() {
  if (props.from == 'edit') {
    try {
      console.log(newItemForm);
      
      const res = await useChildMap.updateStockItemData(
        props.stockItem.id,
        newItemForm
      );
      if (res) {
        $q.notify({
          color: 'positive',
          position: 'bottom',
          message: 'Success',
        });
      }
    } catch (error) {
      $q.notify({
        color: 'negative',
        position: 'bottom',
        message: 'Submit failed',
        icon: 'report_problem',
      });
    } finally {
      emit('submit');
    }
  }
  if (props.from == 'create') {
    try {
      const res = await useChildMap.createStockItemData(newItemForm);
      if (res) {
        $q.notify({
          color: 'positive',
          position: 'bottom',
          message: 'Success',
        });
        if (props.parent_stock_code) {
          const s = await useChildMap.assignChildStockData(
            props.parent_stock_code,
            res.stock_code
          );
        }
      }
    } catch (error) {
      console.log(error);

      $q.notify({
        color: 'negative',
        position: 'bottom',
        message: 'Submit failed',
        icon: 'report_problem',
      });
    } finally {
      emit('submit');
    }
  }
}

async function onSubmit() {
  disableSubmit.value = true;
  await submitForm();
  disableSubmit.value = false;
  emit('submit');
  emit('cancel');
}

function onReset() {
  if (props.stockItem) {
    getStockItemData();
  } else {
    newItemForm.stockCode = '';
    newItemForm.workgroup = '';
    newItemForm.system = '';
    newItemForm.shortDescription = '';
    newItemForm.detailDescription = '';
    newItemForm.dateCode = '';
    newItemForm.swVer = '';
    newItemForm.hwVer = '';
    newItemForm.obsolescence = 0;
    newItemForm.global_regular_cycle_month = 36;
    newItemForm.equipmentClass = '';
    newItemForm.asset_id = '';
    newItemForm.lv1 = '';
    newItemForm.lv2 = '';
    newItemForm.lv3 = '';
    newItemForm.lv4 = '';
    newItemForm.lv5 = '';
  }
}

async function init() {
  getStockItemData();
}

async function importECRelation() {
  const res = await importAssetECRelation(newItemForm.equipmentClass);
  if (res) {
    newItemForm.equipmentClass = res.equipment_class;
    newItemForm.lv1 = res.lv1;
    newItemForm.lv2 = res.lv2;
    newItemForm.lv3 = res.lv3;
    newItemForm.lv4 = res.lv4;
    newItemForm.lv5 = res.lv5;
  }
}

async function importLv4Relation() {
  const res = await importAssetLv4Relation(newItemForm.lv4);
  if (res) {
    newItemForm.equipmentClass = res.equipment_class;
    newItemForm.lv1 = res.lv1;
    newItemForm.lv2 = res.lv2;
    newItemForm.lv3 = res.lv3;
    newItemForm.lv4 = res.lv4;
    newItemForm.lv5 = res.lv5;
  }
}

async function importLv5Relation() {
  const res = await importAssetLv5Relation(newItemForm.lv5);
  if (res) {
    newItemForm.equipmentClass = res.equipment_class;
    newItemForm.lv1 = res.lv1;
    newItemForm.lv2 = res.lv2;
    newItemForm.lv3 = res.lv3;
    newItemForm.lv4 = res.lv4;
    newItemForm.lv5 = res.lv5;
  }
}

const eqClassOptions = [
  'EpOptions',
  'EpOptions',
  'EpOptions',
  'EpOptions',
  'EpOptions',
];

const EpOptions = ref(eqClassOptions);

// const lv1Options = ['lv1'];
// const lv2Options = ['lv2Options'];
// const lv3Options = ['lv3Options'];
// const lv4Options = ['lv4Options'];
// const lv5Options = ['lv5Options'];

const lv1Options = ['lv1'];
const lv2Options = ['lv2Options'];
const lv3Options = ['lv3Options'];
const lv4Options = ['lv4Options'];
const lv5Options = ['lv5Options'];

function filterFn(val: string, update: any) {
  if (val === '') {
    update(() => {
      EpOptions.value = eqClassOptions;

      // here you have access to "ref" which
      // is the Vue reference of the QSelect
    });
    return;
  }

  update(() => {
    const needle = val.toLowerCase();
    EpOptions.value = eqClassOptions.filter(
      (v) => v.toLowerCase().indexOf(needle) > -1
    );
  });
}

function updateCreateFormDateCode(dateCode: string) {
  newItemForm.dateCode = dateCode;
  datePopup.value = false;
}

function dateCodeRule(val: string) {
  if (val == '') {
    return;
  }
  const regex = /^\d{4}\/\d{2}$/;
  return regex.test(val) || 'Date must be in the format "YYYY/MM"';
}

function checkStockCode(val: string) {
  if (val[0] == 's') {
    val = val.toUpperCase();
  }

  const regex = /^(S\d{9}|\d{9})$/;
  return (
    regex.test(val) || 'Stock Code must be in format 9 numbers or S + 9 numbers'
  );
}

/* function versionRule(val: string){
  const pattern = /^([\w\d]+,)*[\w\d]+$/;
  return pattern.test(val)||'Multiple version support with separated by , version1,version2';
} */

//init()

const eqClassStringOptions = ref<string[]>([]);
const lv4StringOptions = ref<string[]>([]);
const lv5StringOptions = ref<string[]>([]);

setTimeout(() => {
  eqClassStringOptions.value = [...inputOptionStore.data.equipmentClass];
  lv4StringOptions.value = [...inputOptionStore.data.lv4];
  lv5StringOptions.value = [...inputOptionStore.data.lv5];
}, 500);

function epClassFilterFn(val: string, update: any) {
  if (val === '') {
    update(() => {
      inputOptionStore.data.equipmentClass = [...eqClassStringOptions.value];
    });
    return;
  }

  update(() => {
    const needle = val.toLowerCase();
    inputOptionStore.data.equipmentClass = eqClassStringOptions.value.filter(
      (v: string) => v.toLowerCase().indexOf(needle) > -1
    );
  });
}

function lv4FilterFn(val: string, update: any) {
  if (val === '') {
    update(() => {
      inputOptionStore.data.lv4 = [...lv4StringOptions.value];
    });
    return;
  }

  update(() => {
    const needle = val.toLowerCase();
    inputOptionStore.data.lv4 = lv4StringOptions.value.filter(
      (v: string) => v.toLowerCase().indexOf(needle) > -1
    );
  });
}

function lv5FilterFn(val: string, update: any) {
  if (val === '') {
    update(() => {
      inputOptionStore.data.lv5 = [...lv5StringOptions.value];
    });
    return;
  }

  update(() => {
    const needle = val.toLowerCase();
    inputOptionStore.data.lv5 = lv5StringOptions.value.filter(
      (v: string) => v.toLowerCase().indexOf(needle) > -1
    );
  });
}
</script>

<style scoped></style>
